using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TerrainLoader : MonoBehaviour
{
    public const int BLOCK_UNIT_SIZE = 16;

    private int atlasWidth = 16;
    private int atlasHeight = 16;

    private Texture2D terrain;
    private Sprite testTerr;

    public Texture LoadedTerrain
    {
        get => terrain;
    }

    private static TerrainLoader instance;

    public static TerrainLoader GetInstance()
    {
        return instance;
    }

    private void Awake()
    {
        instance = this;
        terrain = new Texture2D(BLOCK_UNIT_SIZE * atlasWidth, BLOCK_UNIT_SIZE * atlasHeight);
        terrain.name = "Generated Terrain";

        var stone = Resources.Load<Texture2D>("Textures/Block/stone");
        var grass = Resources.Load<Texture2D>("Textures/Block/grass_top");
        var grassSide = Resources.Load<Texture2D>("Textures/Block/grass_side");
        var dirt = Resources.Load<Texture2D>("Textures/Block/dirt");
        var bedrock = Resources.Load<Texture2D>("Textures/Block/bedrock");
        var craftTable = Resources.Load<Texture2D>("Textures/Block/crafting_table_top");
        var craftTableSide = Resources.Load<Texture2D>("Textures/Block/crafting_table_side");
        var craftTableFront = Resources.Load<Texture2D>("Textures/Block/crafting_table_front");
        var woodenPlank = Resources.Load<Texture2D>("Textures/Block/oak_planks");

        SetBlock(stone, 0);
        SetBlock(grass, 1);
        SetBlock(grassSide, 2);
        SetBlock(dirt, 3);
        SetBlock(bedrock, 4);
        SetBlock(craftTable, 5);
        SetBlock(craftTableFront, 6);
        SetBlock(craftTableSide, 7);
        SetBlock(woodenPlank, 8);


        terrain.filterMode = FilterMode.Point;
        terrain.Apply();

        testTerr = Sprite.Create(terrain, new Rect(0, 0, terrain.width,terrain.height), new Vector2(terrain.width / 2, terrain.height / 2));
        testTerr.name = "Test Terrain Sprite";
    }

    public Vector2[] GetIndexUVs(int index)
    {
        var unitSize = (float)BLOCK_UNIT_SIZE / terrain.width;

        var up = new Vector2(0, unitSize);
        var right = new Vector2(unitSize, 0);
        var origin = new Vector2((index % atlasWidth) * unitSize, (index / atlasWidth) * unitSize);
        return new Vector2[]
        {
            origin,
            origin + up,
            origin + right,
            origin + up + right,
        };
    }

    private void Start()
    {
    }

    private void SetBlock(Texture2D block, int index)
    {
        var origin = new Vector2Int(index % 16 * 16, index / 16 * 16);
        for (int x = 0; x < BLOCK_UNIT_SIZE; x++)
        {
            for (int y = 0; y < BLOCK_UNIT_SIZE; y++)
            {
                terrain.SetPixel(origin.x + x, origin.y + y, block.GetPixel(x, y));
            }
        }
    }
}
